<?php

namespace Modules\Permission\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\DB;
use Modules\Admin\Entities\Admin;

use Modules\RolePermission\Database\Seeders\RolePermissionDatabaseSeeder;

use Spatie\Permission\Models\Role;

class PermissionDatabaseSeeder extends Seeder {
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        Model::unguard();
        $tableNames = config('permission.table_names');
        //忽略外键约束  清空表
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        DB::table('permissions')->truncate();
        DB::table('model_has_permissions')->truncate();
        DB::table('model_has_roles')->truncate();
        DB::table('role_has_permissions')->truncate();
        DB::table('roles')->truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        DB::transaction(function () use ($tableNames) {
            $role_permissions = config('permission.role_permission');
            $date = date('Y-m-d H:i:s');
            if (is_array($role_permissions)) {
                foreach ($role_permissions as $key => $items) {
                    if ($key == "roles" && is_array($items)) {
                        foreach ($items as $item) {
                            Role::create($item);
                        }
                    } else {
                        if ($key == "permissions" && is_array($items)) {
                            foreach ($items as $item) {
                                $item['guard_name']= 'admin';
                                $item['created_at']= $date;
                                $item['updated_at']= $date;
                                DB::table($tableNames['permissions'])->insert($item);
                            }
                        }
                    }
                }
            }
        });

    }
}
